﻿#include "YDemuxer.h"
extern "C"
{
#include "libavformat/avformat.h"
}
/// <summary>
	/// 打开解封装器
	/// </summary>
	/// <param name="url">打开的文件地址（本地路径或网络url）</param>
	/// <returns></returns>
AVFormatContext* YDemuxer::Open(const char* url)
{
	std::unique_lock<std::mutex> lock(mutex);
	AVFormatContext* ic = nullptr;
	AVDictionary* opts = nullptr;
	//av_dict_set(&opts, "rtsp_transport", "tcp", 0);//传输媒体流为tcp协议，默认udp
	av_dict_set(&opts, "stimeout", "1000000", 0);//连接超时1秒
	//打开封装上下文
	auto re = avformat_open_input(&ic,url, nullptr, &opts);
	if (opts)
		av_dict_free(&opts);
	PrintError(re, "avformat_open_input");
	//获取媒体信息
	re = avformat_find_stream_info(ic, nullptr);
	PrintError(re, "avformat_find_stream_info");
	return ic;
}

/// <summary>
/// 读取一帧数据
/// </summary>
/// <param name="pkt">输出数据</param>
/// <returns></returns>
bool YDemuxer::Read(AVPacket* pkt)
{
	std::unique_lock<std::mutex> lock(mutex);
	if (!c_context)return false;
	auto re = av_read_frame(c_context, pkt);
	if (re != 0)
	{
		if (re == AVERROR_EOF) {
			qDebug() << "已经读到结尾了";
		}
		else {
			PrintError(re, "av_read_frame");
		}
		return false;
	}

	return true;
}

bool YDemuxer::Seek(long long pts, int stream_index)
{
	std::unique_lock<std::mutex> lock(mutex);
	if (!c_context)return false;
	auto re = av_seek_frame(c_context, stream_index, pts,
		AVSEEK_FLAG_FRAME | AVSEEK_FLAG_BACKWARD);
	PrintError(re, "Seek->av_seek_frame");
	return true;
}

YDemuxer::YDemuxer()
{
}

YDemuxer::~YDemuxer()
{
}
